<template>
  <div>
    <div class="chart">
      <el-page-header @back="back" style="position: absolute"></el-page-header>
      <template v-for="m in messages">
        <chart-item :message="m"/>
      </template>
    </div>
    <div class="input">
      <el-input v-model="input" type="textarea"
                :autosize="{ minRows: 1, maxRows: 4}"
                resize="none"></el-input>

      <el-button type="primary" size="mini"
                 @click="send">发送</el-button>
    </div>
  </div>
</template>

<script>
import {requests} from "@/utils/request";
import ChartItem from "@/components/chartItem";

export default {
  name: "Chart",
  components: {ChartItem},
  data(){
    return{
      messages:[],
      input:''
    }
  },
  mounted() {
    this.getMessages()
    this.$bus.$on("onmessage",this.onMessage)
  },
  destroyed() {
    this.$bus.$off("onmessage")
  },
  methods:{
    back(){
      this.$router.back()
    },
    //发送消息
      async send(){

      //插入数据库
     await requests.post("message/send",{
        userTo:this.$route.query.id,
        message:this.input
      })
      //重新加载数据刷新页面
        const userid=this.$route.query.id
        requests.get('/message/chart/'+userid).then((res)=>{
          const m=Array(res.data.data)
          console.log(m)
          this.messages.push(res.data.data.pop())
        })
        //清空输入框
        this.input=''
    },
    //获取消息列表
     getMessages(){
      //userid为聊天对象id
      const userid=this.$route.query.id
      requests.get('/message/chart/'+userid).then((res)=>{
        this.messages=res.data.data
      })
    },
    onMessage(m){
      this.messages.push(m)
      console.log(m)
    }
  }
}
</script>

<style>
.chart{
  height: 500px;
  overflow: auto;
}
.input{
  width: 400px;
  padding: 4px;
  margin: auto;
}
</style>